package edu.gzhu.guli.back.service.course.chapter;

import java.util.Optional;

import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;

import edu.gzhu.guli.core.common.ApplicationResult;
import edu.gzhu.guli.core.entity.Chapter;
import edu.gzhu.guli.core.entity.Course;
import edu.gzhu.guli.core.repository.ChapterRepository;
import edu.gzhu.guli.core.repository.CourseRepository;
import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class ChapterService {
  final CourseRepository courseRepository;
  final ChapterRepository chapterRepository;
  final ModelMapper modelMapper;

  // 新增课程章节
  public ApplicationResult<ChapterReadDto> create(Long courseId, ChapterCreateOrEditDto dto) {
    Optional<Course> checkCourse = courseRepository.findById(courseId);
    if (!checkCourse.isPresent()) return ApplicationResult.failure("未找到目标课程");
    Course course = checkCourse.get();

    Chapter chapter = modelMapper.map(dto, Chapter.class);
    chapter.setCourse(course);
    chapter = chapterRepository.save(chapter);
    ChapterReadDto data = modelMapper.map(chapter, ChapterReadDto.class);
    return ApplicationResult.succese(data);
  }

  // 编辑课程章节信息
  public ApplicationResult<ChapterReadDto> edit(Long courseId, Long chapterId, ChapterCreateOrEditDto dto) {
    Optional<Chapter> checkChapter = chapterRepository.findById(chapterId);
    if (!checkChapter.isPresent()) return ApplicationResult.failure("未找到目标章节");
    Chapter chapter = checkChapter.get();
    
    Optional<Course> checkCourse = courseRepository.findById(courseId);
    if (!checkCourse.isPresent()) return ApplicationResult.failure("未找到目标课程");
    Course course = checkCourse.get();

    modelMapper.map(dto, chapter);
    chapter = chapterRepository.save(chapter);
    chapter.setCourse(course);
    ChapterReadDto data = modelMapper.map(chapter, ChapterReadDto.class);
    return ApplicationResult.succese(data);
  }

  // 删除课程章节
  public ApplicationResult<Object> delete(Long chapterId) {
    Optional<Chapter> checkChapter = chapterRepository.findById(chapterId);
    if (!checkChapter.isPresent()) return ApplicationResult.failure("未找到目标章节");
    Chapter chapter = checkChapter.get();
    chapterRepository.delete(chapter);
    return ApplicationResult.succese();
  }
}
